# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Produces C++ file with sorted array of UMA User Actions strings."""

import argparse
import sys
import os

from xml.etree import ElementTree


def not_user_triggered_actions(actions_file_path):
    """Generates list of not-user triggered and non-obsolete UMA User Actions.

    Args:
        actions_file_path: path to actions.xml file
    """
    actions = ElementTree.parse(actions_file_path).getroot()

    for action in actions:
        if action.find('obsolete') is not None:
            continue

        if action.attrib.get('not_user_triggered') == 'true':
          yield action.attrib['name']


def main(actions_file_path, output_file_path):
    """Produces C++ file with sorted array of UMA User Actions strings.

    Array is a global kNotUserTriggeredActions constant in anonymous namespace.

    Args:
        actions_file_path: path to actions.xml file
        output_file_path: path to output C++ file
    """
    actions = not_user_triggered_actions(actions_file_path)
    if not actions:
        sys.stderr.write(
            'There are no not-user triggered and non-obsolete in %s',
            actions_file_path)
        return -1


    with open(output_file_path ,'w') as output_file:
        output_file.write('// Generated by %s\n' % sys.argv[0])
        output_file.write('namespace {\n')
        output_file.write('const char* const kNotUserTriggeredActions[] = {\n')

        for action in sorted(actions):
            output_file.write('  "%s",\n' % action)

        output_file.write('};\n')
        output_file.write('}  // namespace\n')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '-a',
        '--actions',
        help='path to actions.xml file')
    parser.add_argument(
        '-o',
        '--output',
        help='path to output source file')

    args = parser.parse_args()

    sys.exit(main(args.actions, args.output))
